package scala.day02

import scala.io.Source

object Demo12StudentWordCount {
  def main(args:Array[String]):Unit = {
    /**
      * 统计班级的平均年龄
      */
    //1.读取学生数据
    val studens: List[String] = Source.fromFile("data/students.txt").getLines().toList
    //2.取出班级和年龄
    val clazzAndage: List[(String, Int)] = studens.map((student:String) =>{
      val split: Array[String] = student.split(",")
      val age: Int = split(2).toInt
      val clazz: String = split(4)
      //返回一个二元组
      (clazz,age)
    })
    //3.将同一个班级分到同一个组内
    val group: Map[String,List[(String, Int)]] = clazzAndage.groupBy((kv:(String,Int))=>kv._1)
    println(group)
    //4.统计班级的平均年龄
    val calzzAvgAge: Map[String, Double] = group.map((kv:(String,List[(String,Int)]))=>{
      val clazz: String = kv._1
      val clazzs: List[(String, Int)] = kv._2
      //取出年龄
      val ages: List[Int] = clazzs.map((i:(String,Int)) =>i._2)
      val avgAge: Double = ages.sum / ages.length.toDouble
      (clazz,avgAge)
    })
    calzzAvgAge.foreach(println)
  }
}
